﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BW.Mes.WinForms.Process
{
    public partial class AddProcessForm : DevExpress.XtraEditors.XtraForm
    {
        // 添加部门列表和字典用于存储部门数据
        private List<Department> departments = new List<Department>();
        private Dictionary<string, long> departmentNameToId = new Dictionary<string, long>();
        
        // 添加车间列表和字典用于存储车间数据
        private List<Workshop> workshops = new List<Workshop>();
        private Dictionary<string, long> workshopNameToId = new Dictionary<string, long>();
      
        // 声明委托和事件
        public delegate void ProcessAddedEventHandler(object sender, EventArgs e);
        public event ProcessAddedEventHandler ProcessAdded;

        // 触发事件的方法
        protected virtual void OnProcessAdded()
        {
            ProcessAdded?.Invoke(this, EventArgs.Empty);
        }

        public AddProcessForm()
        {
            InitializeComponent();
        }
        

        private void labelControl1_Click(object sender, EventArgs e)
        {

        }

        private void labelControl4_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 添加按钮方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            // 获取选中部门的ID
            long departmentId = 0;
            if (!string.IsNullOrEmpty(comboBoxEdit1.Text) && departmentNameToId.ContainsKey(comboBoxEdit1.Text))
            {
                departmentId = departmentNameToId[comboBoxEdit1.Text];
            }
            
            // 获取选中车间的ID
            long workshopId = 0;
            if (!string.IsNullOrEmpty(comboBoxEdit2.Text) && workshopNameToId.ContainsKey(comboBoxEdit2.Text))
            {
                workshopId = workshopNameToId[comboBoxEdit2.Text];
            }

            ///将文本框中的内容赋给实体
            var model = new AddProcessModel
            {
                processName = textEdit1.Text,
                processExplain = textEdit2.Text,
                processDesc = textEdit3.Text,
                processHead = textEdit4.Text,
                processDepartment = departmentId, // 使用ID而不是文本
                processworkshop = workshopId, // 使用ID而不是文本
                processMaterials = textEdit7.Text,
                processadEnable = radioGroup1.SelectedIndex == 1 // 假设1为"是"
            };
            ///把表单数据以 POST 方式发送到后端接口
            using (var client = new HttpClient())
            {
                /// 设置请求地址（路由后缀）
                client.BaseAddress = new Uri("http://120.26.197.100:8022");
                ///// 创建 JSON 数据(转数据类型)
                var json = JsonConvert.SerializeObject(model);
                /// 创建请求内容(指定编码为 UTF-8，内容类型为 application/json)
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                /// 发送 POST 请求
                var response = await client.PostAsync("/T5/ProcessModel/AddProcessModel", content);
                ///判断是否成功
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("添加成功！");
                    
                    // 触发事件通知ProcessDataForm
                    OnProcessAdded();
                    
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("添加失败：" + response.ReasonPhrase);
                }
            }
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void comboBoxEdit2_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 可以在这里添加选择车间后的处理逻辑
        }

        private async void AddProcessForm_Load(object sender, EventArgs e)
        {
            // 窗体加载时获取部门数据和车间数据
            await LoadDepartments();
            await LoadWorkshops();
        }

        /// <summary>
        /// 从API获取部门数据并填充下拉框
        /// </summary>
        private async Task LoadDepartments()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022");
                    var response = await client.GetAsync("/T5/Department/ShowDepartments");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult<List<Department>>>(content);
                        
                        if (result != null  && result.Data != null)
                        {
                            departments = result.Data;
                            
                            // 清空现有项
                            comboBoxEdit1.Properties.Items.Clear();
                            departmentNameToId.Clear();
                            
                            // 填充下拉框和字典
                            foreach (var dept in departments)
                            {
                                comboBoxEdit1.Properties.Items.Add(dept.departmentName);
                                departmentNameToId[dept.departmentName] = dept.Id;
                            }
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取部门数据失败：" + response.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("获取部门数据出错：" + ex.Message);
            }
        }
        
        /// <summary>
        /// 从API获取车间数据并填充下拉框
        /// </summary>
        private async Task LoadWorkshops()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022");
                    var response2 = await client.GetAsync("/T2/Workshop/ShowWorkshop");
                    
                    if (response2.IsSuccessStatusCode)
                    {
                        var content2 = await response2.Content.ReadAsStringAsync();
                        var result2 = JsonConvert.DeserializeObject<ApiResult<List<Workshop>>>(content2);
                        
                        if (result2 != null  && result2.Data != null)
                        {
                            workshops = result2.Data;
                            
                            // 清空现有项
                            comboBoxEdit2.Properties.Items.Clear();
                            workshopNameToId.Clear();
                            
                            // 填充下拉框和字典
                            foreach (var workshop in workshops)
                            {
                                comboBoxEdit2.Properties.Items.Add(workshop.workshopName);
                                workshopNameToId[workshop.workshopName] = workshop.Id;
                            }
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("获取车间数据失败：" + response2.ReasonPhrase);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("获取车间数据出错：" + ex.Message);
            }
        }


        /// <summary>
        /// 需要添加实体
        /// </summary>
        public class AddProcessModel
        {
            public string processName { get; set; }
            public string processExplain { get; set; }
            public string processDesc { get; set; }
            public string processHead { get; set; }
            public long processDepartment { get; set; }
            public long processworkshop { get; set; }
            public string processMaterials { get; set; }
            public bool processadEnable { get; set; }
        }

        /// <summary>
        /// 部门实体类
        /// </summary>
        public class Department
        {
            public long Id { get; set; }
            public string departmentName { get; set; }
        }
        
        /// <summary>
        /// 车间实体类
        /// </summary>
        public class Workshop
        {
            public long Id { get; set; }
            public string workshopName { get; set; }
        }

        /// <summary>
        /// API返回结果包装类
        /// </summary>
        public class ApiResult<T>
        {
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public T Data { get; set; }
        }

        private void comboBoxEdit1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 可以在这里添加选择部门后的处理逻辑
        }
    }
}